package org.javaexpert.spaces.masterworker.ui.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.javaexpert.spaces.masterworker.TaskMonitor;
import org.javaexpert.spaces.masterworker.ui.client.SpacesStatsService;
import org.javaexpert.spaces.masterworker.ui.client.TaskStatusData;
import static org.javaexpert.spaces.util.SpaceUtils.findSpace;
import static org.javaexpert.spaces.util.SpaceUtils.findTransactionManager;
import org.javaexpert.spaces.util.TransactionTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;

public class SpacesStatsServiceImpl extends RemoteServiceServlet implements SpacesStatsService {
    private transient TaskMonitor taskBag;

    public TaskMonitor getTaskBag() throws Exception, ClassNotFoundException {
        if (taskBag == null) taskBag = new TaskMonitor( findSpace("myspace"), new TransactionTemplate( findTransactionManager()));
        return taskBag;
    }

    public SpacesStatsServiceImpl() throws Exception {
    }


    public TaskStatusData[] getTaskStatuses(boolean hideFinished) throws Exception {
        List<TaskStatusData> res = new ArrayList<TaskStatusData>();
        for(org.javaexpert.spaces.masterworker.TaskStatusData s: getTaskBag().taskStatuses()){
            TaskStatusData tsd =  new TaskStatusData();
            tsd.taskId = s.taskId;
            tsd.status = s.status.toString();
            tsd.finished = s.finished;
            tsd.workerId = s.workerId;
            tsd.startTime = s.startTime;
            tsd.finishTime = s.finishTime;
            tsd.comment = s.comment;
            tsd.retryCount = s.retryCount;

            if (!(hideFinished && s.finished)) res.add(tsd);
        }
        Collections.sort(res, new Comparator<TaskStatusData>() {
            public int compare(TaskStatusData taskStatusData, TaskStatusData taskStatusData1) {
                return taskStatusData.status.compareTo(taskStatusData1.status);
            }
        });
        return res.toArray(new TaskStatusData[0]);
    }
}
